﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;

namespace FineUI.Examples
{
    public partial class user_view_document : System.Web.UI.Page
    {

        private string _htmlFileName;

        protected void Page_Load(object sender, EventArgs e)
        {
            string strFilename = Session["Doc_Path"].ToString();

              _htmlFileName = WordToHtml((object)strFilename);

              findUsedFromHtml(getHtml(_htmlFileName), strFilename);

              Label1.Text = CKEditorControl1.Text;
        }

        /// <summary>
        /// word转成html
        /// </summary>
        /// <param name="wordFileName"></param>
        private string WordToHtml(object wordFileName)
        {
            //在此处放置用户代码以初始化页面
            Application word = new Application();
            Type wordType = word.GetType();
            Documents docs = word.Documents;

            //打开文件
            Type docsType = docs.GetType();
            Document doc = (Document)docsType.InvokeMember("Open",
            System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });

            //转换格式，另存为
            Type docType = doc.GetType();

            string wordSaveFileName = wordFileName.ToString();
            string strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html";
            object saveFileName = (object)strSaveFileName;
            //下面是Microsoft Word 9 Object Library的写法，如果是10，可能写成：

            docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
             null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML });

            ///其它格式：
            ///wdFormatHTML
            ///wdFormatDocument
            ///wdFormatDOSText
            ///wdFormatDOSTextLineBreaks
            ///wdFormatEncodedText
            ///wdFormatRTF
            ///wdFormatTemplate
            ///wdFormatText
            ///wdFormatTextLineBreaks
            ///wdFormatUnicodeText
            //docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
            // null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML });

            docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
             null, doc, null);

            //退出 Word
            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod,
             null, word, null);

            return saveFileName.ToString();
        }



        /// <summary>
        /// 读取html文件，返回字符串
        /// </summary>
        /// <param name="strHtmlFileName"></param>
        /// <returns></returns>
        private string getHtml(string strHtmlFileName)
        {
            System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312");

            StreamReader sr = new StreamReader(strHtmlFileName, encoding);

            string str = sr.ReadToEnd();

            sr.Close();

            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        private void findUsedFromHtml(string strHtml, string strFileName)
        {
            string strStyle;
            string strBody;

            // stytle 部分
            int index = 0;
            int intStyleStart = 0;
            int intStyleEnd = 0;

            while (index < strHtml.Length)
            {
                int intStyleStartTmp = strHtml.IndexOf("<style>", index);
                if (intStyleStartTmp == -1)
                {
                    break;
                }
                int intContentStart = strHtml.IndexOf("<!--", intStyleStartTmp);
                if (intContentStart - intStyleStartTmp == 9)
                {
                    intStyleStart = intStyleStartTmp;
                    break;
                }
                else
                {
                    index = intStyleStartTmp + 7;
                }
            }

            index = 0;
            while (index < strHtml.Length)
            {
                int intContentEndTmp = strHtml.IndexOf("-->", index);
                if (intContentEndTmp == -1)
                {
                    break;
                }
                int intStyleEndTmp = strHtml.IndexOf("</style>", intContentEndTmp);
                if (intStyleEndTmp - intContentEndTmp == 5)
                {
                    intStyleEnd = intStyleEndTmp;
                    break;
                }
                else
                {
                    index = intContentEndTmp + 4;
                }
            }

            strStyle = strHtml.Substring(intStyleStart, intStyleEnd - intStyleStart + 8);

            // Body部分
            int bodyStart = strHtml.IndexOf("<body");
            int bodyEnd = strHtml.IndexOf("</body>");

            strBody = strHtml.Substring(bodyStart, bodyEnd - bodyStart + 7);

            //替换图片地址
            string fullName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
            string strOld = fullName.Replace("docx", "files");
            strOld = strOld.Replace("doc", "files");
            //string strNew = Page.Request.ApplicationPath + "/Portals/0/WordImport/" + strOld;
            //string strNew = Server.MapPath("~/") + "Portals/0/WordImport/" + strOld;
            //string strNew1 =strNew.Replace(@"\", "//");
           
            //读取session中的当前用户类型是学生还是教师
            string currentFlag = Session["Doc_Flag"].ToString();

            //得到文档的真正途径（学生和教师存放在不同的文件夹中）
            string strNew = "/document/" + currentFlag +"/"+ strOld;
            strBody = strBody.Replace(strOld, strNew);

            strBody = strBody.Replace("v:imagedata", "img");
            strBody = strBody.Replace("<:imagedata>", "");

            //this.TextBox1.Text = strBody;
            this.TextArea1.InnerText = strStyle;
            this.Textarea2.InnerText = strBody;

            CKEditorControl1.Text = strBody;


        }

    }
}